import { h, render } from 'vue'
import XtxMessage from './index.vue'

type ParamsType = {
  type: 'success' | 'error' | 'warning'
  message: string
  duration?: number
}

const MessageContainer = document.createElement('div')
MessageContainer.className = 'Xtx-Message'
document.body.appendChild(MessageContainer)

export default function Message({
  type,
  message,
  duration = 3000
}: ParamsType) {
  // 1. 创建虚拟DOM
  const vnode = h(XtxMessage, { type, message, key: Date.now(), duration })

  // 2. 挂载虚拟DOM
  render(vnode, MessageContainer)

  // 3. 延时清除虚拟DOM
  // setTimeout(() => {
  //   render(null, MessageContainer)
  // }, duration)
}

// 拓展消息框函数 => 函数本身也是对象，给对象上添加方法
Message.success = (message: string, duration = 3000) => {
  Message({ type: 'success', message, duration })
}

Message.error = (message: string, duration = 3000) => {
  Message({ type: 'error', message, duration })
}

Message.warning = (message: string, duration = 3000) => {
  Message({ type: 'warning', message, duration })
}
